package com.hmall.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component//当类的逻辑简单且不需要复杂的配置时，可以直接使用 @Component 注解。和后续的MvcConfig 形成对比
@RequiredArgsConstructor
public class  AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    //不包括拦截的路径
    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要拦截
        if(isExclude(request.getPath().toString())){
            //为不拦截的路径直接放行
            return chain.filter(exchange);
        }
        //3.从请求头中获取token进行登录令牌校验
        List<String> headers = request.getHeaders().get("authorization");

        String token = null;
        if(CollUtil.isNotEmpty(headers)){
             token = headers.get(0);
        }
        Long userId = null;
        try {
             userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //如果异常捕获异常发送401而不是直接抛异常
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
            //在此拦截不会往后运行
            return response.setComplete();
        }
        // 5.如果有效，传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate().
                request(builder -> builder.header("user-info", userInfo)).build();
        //6.放行执行后续过滤器
        return chain.filter(serverWebExchange);
    }

    private boolean isExclude(String antpath) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath, antpath)){//match方法参数1是excludePath，参数2是请求路径
                //匹配成功放行
                return true;//
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        // 数字越小，优先级越高过滤器越先执行
        return 0;
    }
}
